package cn.py.boot_lua.handler.generic;

import cn.py.boot_lua.handler.admin.RequestTask;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

@Service
public class GenericQueueService {
    // 创建容器
    private final Map<String, BlockingQueue<RequestTask>> queueMap = new ConcurrentHashMap<>();

    // 添加任务
    public void addToQueue(String queueKey, RequestTask task) {
        queueMap.computeIfAbsent(queueKey, k -> new LinkedBlockingQueue<>()).add(task);
    }

    // 获取任务，非阻塞方式
    public RequestTask pollFromQueue(String queueKey) {
        BlockingQueue <RequestTask> queue = queueMap.get(queueKey);
        return queue == null ? null : queue.poll();
    }

    // 获取队列大小
    public int getQueueSize(String queueKey) {
        BlockingQueue <RequestTask> queue = queueMap.get(queueKey);
        return queue == null ? 0 : queue.size();
    }

}
